package org.example.temporal;

import org.example.temporal.ScheduledEvent;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;

public class TemporalExampleMain {
    public static final EntityManagerFactory factory = Persistence.createEntityManagerFactory("my-persistence-unit");
    public static void main(String[] args) {
        persistEvent();
        findEvent();
        nativeQuery();
    }

    private static void persistEvent(){
        ScheduledEvent scheduledEvent = ScheduledEvent.getInstance("Test event",
                LocalDate.of(2016,6,1),
                LocalTime.of(9,30,45),
                LocalTime.of(11,45,30));
        System.err.println("-- persisting entity --");
        System.err.println(scheduledEvent);
        EntityManager entityManager = factory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.persist(scheduledEvent);
        entityManager.getTransaction().commit();
        entityManager.close();
    }

    private static void findEvent(){
        System.err.println("-- find entity --");
        EntityManager entityManager = factory.createEntityManager();
        ScheduledEvent scheduledEvent = entityManager.find(ScheduledEvent.class,1L);
        System.err.println(scheduledEvent);
        entityManager.close();
    }

    private static void nativeQuery(){
        EntityManager em = factory.createEntityManager();
        System.err.println("-- native query --");
        Query query = em.createQuery("select CONCAT('start=',e.start, ' end=', e.end, ' date=',e.date,' eventCreated=',e.eventCreated) from ScheduledEvent  e");
        List list = query.getResultList();
        for (Object o : list) {
            if (o instanceof Object[]) {
                System.err.println(Arrays.toString((Object[]) o));
            }else{
                System.err.println(o);
            }
        }
        em.close();
    }
}
